package com.gitee.controller;

import com.gitee.bo.RoleBo;
import com.gitee.bo.RolePermissionBo;
import com.gitee.enums.ResponseEnum;
import com.gitee.pojo.Role;
import com.gitee.service.IPermissionService;
import com.gitee.service.IRolePermissionService;
import com.gitee.service.IRoleService;
import com.gitee.vo.PermissionVo;
import com.gitee.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    @Autowired
    private IPermissionService permissionService;

    /**
     * 角色列表
     * @return
     */
    @GetMapping
    public ResponseVo<List<Role>> list() {
        List<Role> roles = roleService.list();
        return ResponseVo.ok(roles);
    }

    /**
     * 添加角色
     * @param roleBo
     * @return
     */
    @PostMapping
    public ResponseVo<String> add(@RequestBody RoleBo roleBo) {
        roleService.addRole(roleBo);
        return ResponseVo.ok(ResponseEnum.ADD_SUCCESS);
    }

    /**
     * 更新角色
     * @param roleBo
     * @param roleId
     * @return
     */
    @PutMapping("/{roleId}")
    public ResponseVo<String> update(@RequestBody RoleBo roleBo, @PathVariable Integer roleId) {
        roleService.updateRole(roleBo, roleId);
        return ResponseVo.ok(ResponseEnum.UPDATE_SUCCESS);
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @DeleteMapping("/{roleId}")
    public ResponseVo<String> delete(@PathVariable Integer roleId) {
        roleService.deleteRole(roleId);
        return ResponseVo.ok(ResponseEnum.DELETE_SUCCESS);
    }

    /**
     * 获取菜单树
     * @return
     */
    @GetMapping("/permission/tree")
    public ResponseVo<List<PermissionVo>> menuTree() {
        List<PermissionVo> permissionVos = permissionService.getMenuTree();
        return ResponseVo.ok(permissionVos);
    }

    /**
     * 根据角色id获取具有的权限列表
     * @param roleId
     * @return
     */
    @GetMapping("/permission/{roleId}")
    public ResponseVo<List<Integer>> getPermissionIdsByRoleId(@PathVariable Integer roleId) {
        List<Integer> permissionIds = rolePermissionService.listByRoleId(roleId);
        return ResponseVo.ok(permissionIds);
    }

    /**
     * 根据角色id更新权限
     * @param rolePermissionBo
     * @param roleId
     * @return
     */
    @PutMapping("/permission/{roleId}")
    public ResponseVo<String> updatePermissionByRoleId(@RequestBody RolePermissionBo rolePermissionBo, @PathVariable Integer roleId) {
        rolePermissionService.updateByRoleId(roleId, rolePermissionBo);
        return ResponseVo.ok(ResponseEnum.UPDATE_SUCCESS);
    }
}
